//
//  CCPTakePicturesController.m
//  CCPCustomCamera
//
//  Created by C CP on 16/9/22.
//  Copyright © 2016年 C CP. All rights reserved.
//

#import "CCPTakePicturesController.h"
#import <AVFoundation/AVFoundation.h>
//处理相册的系统框架
#import <AssetsLibrary/AssetsLibrary.h>
#import "AliImageReshapeController.h"
#import "MotionOrientation.h"
#import "CCPCameraView.h"

#define BUNDLE(imgName) [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"BoPhotoPicker.bundle/images/%@@2x.png",imgName]]]

typedef void(^lightBlock)();

@interface CCPTakePicturesController ()<UIGestureRecognizerDelegate,AVCaptureMetadataOutputObjectsDelegate,ALiImageReshapeDelegate>

//负责输入和输出设备之间的数据传递
@property(nonatomic,strong) AVCaptureSession *captureSession;
//负责从AVCaptureDevice获得输入数据
@property(nonatomic,strong) AVCaptureDeviceInput *captureDeviceInput;
//照片输出流
@property(nonatomic,strong) AVCaptureStillImageOutput *captureStillImageOutput;
//相机拍摄预览图层
@property(nonatomic,strong) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
/**
 *  用来获取相机设备的一些属性
 */
@property (nonatomic,strong)AVCaptureDevice *device;

@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) UIView *bottomView;
@property(nonatomic,strong) UIView *contentView;
//牌照按钮
@property(nonatomic,strong) UIButton *takeButton;
//切换摄像头按钮
@property(nonatomic,strong) UIButton *switchCameraButton;
//切换闪光效果
@property(nonatomic,strong) UIButton *flashButton;
//关闭按钮
@property(nonatomic,strong) UIButton *closeButton;
/**
 *  记录屏幕的旋转方向
 */
@property (nonatomic,assign) UIDeviceOrientation deviceOrientation;
/**
 *  闪光灯状态
 */
@property (nonatomic,assign) NSInteger lightCameraState;
@end

@implementation CCPTakePicturesController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    //默认开启截图功能
//    self.isCanCut = YES;
    //判断相机 是否可以使用
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        NSLog(@"sorry, no camera or camera is unavailable.");
        return;
    }
    [[MotionOrientation sharedInstance] startAccelerometerUpdates];
    
    self.deviceOrientation = UIDeviceOrientationPortrait;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(motionDeviceOrientationChanged:) name:MotionOrientationChangedNotification object:nil];
    
    [self initLayout];

}

//初始化布局
-(void)initLayout{
    CGSize viewSize = self.view.bounds.size;
    //头部
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewSize.width, 64)];
    _headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_headView];
    
    _switchCameraButton = [[UIButton alloc] initWithFrame:CGRectMake(viewSize.width-59, 20, 44, 44)];
    [_switchCameraButton setImage:BUNDLE(@"camera_rotate") forState:UIControlStateNormal];
    [_switchCameraButton setImageEdgeInsets:UIEdgeInsetsMake(12,10,12,10)];
    [_switchCameraButton addTarget:self action:@selector(clickchangeButton) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:_switchCameraButton];
    
    _flashButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(_switchCameraButton.frame)-59, CGRectGetMinY(_switchCameraButton.frame), 44, 44)];
    [_flashButton setImage:BUNDLE(@"high_light") forState:UIControlStateNormal];
    [_flashButton setImageEdgeInsets:UIEdgeInsetsMake(10,10,10,10)];
    [_flashButton addTarget:self action:@selector(clickLightButton:) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:_flashButton];
    
    _closeButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 20, 44, 44)];
    [_closeButton setImage:BUNDLE(@"cancel") forState:UIControlStateNormal];
    [_closeButton setImageEdgeInsets:UIEdgeInsetsMake(14,14,14,14)];
    [_closeButton addTarget:self action:@selector(cancelDidClick) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:_closeButton];
    
    //相机拍摄预览图层
    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_headView.frame), viewSize.width, viewSize.height-64)];
    _contentView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_contentView];
    
    //底部
    //    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, viewSize.height-64, viewSize.width, 44)];
    ////    _bottomView.backgroundColor = [UIColor whiteColor];
    //    [self.view addSubview:_bottomView];
    
    _takeButton = [[UIButton alloc] initWithFrame:CGRectMake((viewSize.width-50)/2, viewSize.height-70, 50, 50)];
    [_takeButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_takeButton setImage:BUNDLE(@"camera") forState:UIControlStateNormal];
    //    [takeButton setImageEdgeInsets:UIEdgeInsetsMake(12,10,12,10)];
    [self.view addSubview:_takeButton];
    
    
    [_takeButton addTarget:self action:@selector(tackButtonClick) forControlEvents:UIControlEventTouchUpInside];
}

-(void)cancelDidClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //    UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 200)];
    //    [self.view addSubview:layerView];
    
    
    //初始化会话
    _captureSession = [[AVCaptureSession alloc] init];
    
    self.device = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack]; //取得后置摄像头
    if (!self.device) {
        NSLog(@"取得后置摄像头出现问题.");
        return;
    }
    
    NSError *error = nil;
    _captureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错,错误原因:%@",error.localizedDescription);
        return;
    }
    
    //初始化设备输出对象,用于获得输出数据
    _captureStillImageOutput  = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
    [_captureStillImageOutput setOutputSettings:outputSettings];//输出设置
    
    //将设备输入添加到会话中
    if ([_captureSession canAddInput:_captureDeviceInput]) {
        [_captureSession addInput:_captureDeviceInput];
    }
    
    //将设备输出添加到会话中
    if ([_captureSession canAddOutput:_captureStillImageOutput]) {
        [_captureSession addOutput:_captureStillImageOutput];
    }
    
    //创建视频预览层,用于实时展示摄像头状态
    _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
    
    CALayer *layer = _contentView.layer;
    layer.masksToBounds = YES;
    
    _captureVideoPreviewLayer.frame = layer.bounds;
    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//填充模式
    
    [layer addSublayer:_captureVideoPreviewLayer];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //KVO 监听对焦回调
//    [self.device addObserver:self forKeyPath:@"adjustingFocus" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.captureSession startRunning];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //移除KVO
//    [self.device removeObserver:self forKeyPath:@"adjustingFocus"];
    
    [self.captureSession stopRunning];
}

-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    for (AVCaptureDevice *camera  in cameras) {
        if ([camera position] == position) {
            return camera;
        }
    }
    return nil;
}

-(void)tackButtonClick{
    //根据设备输出获得连接
    AVCaptureConnection *captureConnection = [self.captureStillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    
    //获取输出视图的展示方向
    AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation: self.deviceOrientation];
    
    [captureConnection setVideoOrientation:avcaptureOrientation];
    
    //根据连接取得设备输出的数据
    [self.captureStillImageOutput captureStillImageAsynchronouslyFromConnection:captureConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer) {
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            
            UIImage *image = [UIImage imageWithData:imageData];
            
            if (self.isCanCut) {
                AliImageReshapeController *vc = [[AliImageReshapeController alloc] init];
                vc.sourceImage = image;
                vc.reshapeScale = 16./9.;
                vc.delegate = self;
                [self presentViewController:vc animated:YES completion:nil];
            }else{
                if ([self.delegate respondsToSelector:@selector(photograph:)]) {
                    [self.delegate photograph:image];
                }
            }
            
        }
    }];
}

#pragma mark -镜头切换
- (void) clickchangeButton {
    // 翻转
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
    [UIView commitAnimations];
    
    NSArray *inputs = _captureSession.inputs;
    for ( AVCaptureDeviceInput *input in inputs ) {
        AVCaptureDevice *device = input.device;
        if ( [device hasMediaType:AVMediaTypeVideo] ) {
            AVCaptureDevicePosition position = device.position;
            AVCaptureDevice *newCamera = nil;
            AVCaptureDeviceInput *newInput = nil;
            
            if (position == AVCaptureDevicePositionFront)
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            else
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            
            [_captureSession beginConfiguration];
            [_captureSession removeInput:input];
            [_captureSession addInput:newInput];
            [_captureSession commitConfiguration];
            break;
        }
    }
}

#pragma mark -相机状态
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position )
            return device;
    return nil;
}

#pragma mark -图片方向
- (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)deviceOrientation;
    if ( deviceOrientation == UIDeviceOrientationLandscapeLeft )
        result = AVCaptureVideoOrientationLandscapeRight;
    else if ( deviceOrientation == UIDeviceOrientationLandscapeRight )
        result = AVCaptureVideoOrientationLandscapeLeft;
    return result;
}

#pragma mark -加速计通知,监听手机方向
- (void)motionDeviceOrientationChanged:(NSNotification *)notification

{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.deviceOrientation = [MotionOrientation sharedInstance].deviceOrientation;
        if (self.deviceOrientation == UIDeviceOrientationLandscapeLeft) {
            [UIView animateWithDuration:1 animations:^{
                _takeButton.transform = CGAffineTransformMakeRotation(M_PI/2);
                _switchCameraButton.transform = CGAffineTransformMakeRotation(M_PI/2);
                _flashButton.transform = CGAffineTransformMakeRotation(M_PI/2);
                _closeButton.transform = CGAffineTransformMakeRotation(M_PI/2);
            }];
        }else{
            [UIView animateWithDuration:1 animations:^{
                _takeButton.transform=CGAffineTransformIdentity;
                _switchCameraButton.transform = CGAffineTransformIdentity;
                _flashButton.transform = CGAffineTransformIdentity;
                _closeButton.transform = CGAffineTransformIdentity;
            }];
        }
        NSLog(@"********%ld",(long)self.deviceOrientation);
    });
}

#pragma mark - 闪光灯的状态
- (void) clickLightButton:(UIButton *)sender {
    
    if (self.lightCameraState < 0) {
        self.lightCameraState = 0;
    }
    self.lightCameraState ++;
    if (self.lightCameraState >= 4) {
        self.lightCameraState = 1;
    }
    AVCaptureFlashMode mode;
    
    switch (self.lightCameraState) {
        case 1:
            mode = AVCaptureFlashModeOn;
            
            [sender setImage:BUNDLE(@"high_light_a") forState:UIControlStateNormal];
            
            break;
        case 2:
            mode = AVCaptureFlashModeAuto;
            [sender setImage:BUNDLE(@"high_light") forState:UIControlStateNormal];
            
            break;
        case 3:
            mode = AVCaptureFlashModeOff;
            
            [sender setImage:BUNDLE(@"high_light_w") forState:UIControlStateNormal];
            break;
        default:
            mode = AVCaptureFlashModeOff;
            
            [sender setImage:BUNDLE(@"high_light_w") forState:UIControlStateNormal];
            break;
    }
    if ([self.device isFlashModeSupported:mode])
    {
        [self flashLightModel:^{
            
            [self.device setFlashMode:mode];
        }];
    }
}

- (void) flashLightModel:(lightBlock) lightBlock{
    if (!lightBlock) return;
    [_captureSession beginConfiguration];
    [self.device lockForConfiguration:nil];
    lightBlock();
    [self.device unlockForConfiguration];
    [_captureSession commitConfiguration];
    [_captureSession startRunning];
}

-(void)imageReshaperController:(AliImageReshapeController *)reshaper didFinishPickingMediaWithInfo:(UIImage *)image{
    if ([self.delegate respondsToSelector:@selector(photograph:)]) {
        [self.delegate photograph:image];
    }
}


@end
